package cn.dai.servlet;

import cn.dai.pojo.JsonResult;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @author ArkD42
 * @file OA Sys
 * @create 2020 - 06 - 16 - 13:41
 */
public abstract class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 地址参数为act统一处理，方法的调用
        String act = req.getParameter("act");

        if (act == null) act = "index"; // 登陆页没有参数就自己加一个

        // 获取子类的字节实例
        Class<? extends BaseServlet> subClass = this.getClass();

        try {
            // 通过字节实例的newInstance();获取子类的实例
            BaseServlet baseServlet = subClass.newInstance();

            // 获取这个类的独有的方法，参数是方法的名字和需要注入的参数的类型
            // 只要是字节对象就行 req.getClass(); resp.getClass();
            Method declaredMethod = subClass.getDeclaredMethod(act, HttpServletRequest.class, HttpServletResponse.class);

            // 方法的返回值
            Object after = declaredMethod.invoke(baseServlet, req, resp);

            // 如果是String类型，那么就知道是要转发和重定向了
            if (after instanceof String) {
                String url = (String) after;

                if (url.contains("forward:")) req.getRequestDispatcher(url.substring(8)).forward(req,resp);
                else if (url.contains("redirect:")) resp.sendRedirect(req.getContextPath() + url.substring(9));

                // 如果是Json结果对象，那么就知道是要接受Ajax请求，然后给前端传JSON数据了
            } else if (after instanceof JsonResult) {
                JsonResult jsonResult = (JsonResult) after;
                String jsonString = JSON.toJSONString(jsonResult);
                // 转换，然后输出
                PrintWriter writer = resp.getWriter();
                writer.println(jsonString);
            }
            // 如果还要返回处理什么在后面继续添加
            // ......

        } catch (Exception e) {
            e.printStackTrace();
            resp.sendRedirect(req.getContextPath() + "/错误页");
            
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
